<?php
declare (strict_types=1);

namespace app\middleware;


use app\common\model\AdminRole;
use app\common\model\OperationLog;
use thans\jwt\facade\JWTAuth;
use think\facade\Db;

class Admin
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //获取控制器名字
        $controller = request()->controller();
        //获取方法名字
        $action = request()->action();
        // 如果执行到这里了 -- 表明 必须验证通过以后才可以继承访问
        try {
            $result = JWTAuth::auth();//token验证
            $admin_id = $result['admin_id'];
            $type = $result['type'];
            if ($type != 'admin') throw new \Exception('登录失效');
            if (empty(session('admin')) && env('APP_DEBUG') != 1) throw new \Exception('登录失效');
        } catch (\Exception $e) {
            // 验证失败
            return json([
                'code' => -5,
                'msg' => "登录失效",
                'data' => []
            ]);
        }
        $route_title = Db::name("route")
            ->where([['controller', '=', $controller]])
            ->value('title');
        //写入后台操作记录
        (new OperationLog())->save([
            'ip_val' => request()->ip(),
            'admin_id' => $admin_id,
            'remarks' => $controller == "Index" ? "首页" : $route_title,
            'controller' => $controller,
            'action' => $action,
            'careful' => "{$controller}/{$action}",
        ]);
        $admin = Db::name("admin")
            ->where(['id' => $admin_id])
            ->find();
        //首页接口不验证  不验证超级管理员和上传接口
        if ($admin['id'] != 1 && $controller != 'admin.Upload') {
            $admin_role = (new AdminRole())
                ->where([
                    'id' => $admin['role_id'],
                    'delete_time' => 0,
                ])
                ->find();

            if (empty($admin_role)) {
                return json([
                    'code' => -10,
                    'msg' => "权限不足",
                    'data' => []
                ]);
            }
            //查询是否有路由权限
            $route = Db::name("route")
                ->where([
                    ['controller', '=', $controller],
                    ['action', '=', $action],
                    ['id', 'in', $admin_role->role_id],
                ])
                ->value('id');
            if (empty($route)) {//判断权限
                return json([
                    'code' => -10,
                    'msg' => "权限不足",
                    'data' => []
                ]);
            }
        }
        return $next($request);
    }

}
